#include <bits/stdc++.h>

#define in read()
#define fi first
#define se second
#define pb push_back
#define rep(i, x, y) for(int i = (x); i <= (y); i++)
#define per(i, x, y) for(int i = (x); i >= (y); i--)

using namespace std;

typedef long long ll;
typedef double db;
typedef vector < int > vec;
typedef pair < int , int > pii;

int read() {
    int x = 0; bool f = 0; char ch = getchar(); while(!isdigit(ch)) f |= ch == '-',ch = getchar();
    while(isdigit(ch)) x = x * 10 + (ch ^ 48),ch = getchar(); return f ? -x : x;
}

const int N = 1e5 + 10;
const int mod = 1e9 + 7;

int a[N], n, deg[N], stk[N], top, vis[N], ftlen[N], tot[N], f[N];
bool isc[N];
ll ans = 1;

void work(int x) {
//	cerr << x << endl;
	int lst = 0, ffl = 0, fflen = 0; top = 0;
	while(isc[x]) {
		++top; isc[x] = false;
		if(ftlen[x]) {
//			cerr << lst << " " << top << " " << ftlen[x] << endl;
			if(!ffl) ffl = top, fflen = ftlen[x];
			else ans = ans * ((ftlen[x] <= top - lst) + (ftlen[x] < top - lst)) % mod;
			lst = top;
//			cerr << ans << endl;
		}
		x = a[x];
	}
	if(!ffl) tot[top]++;
	else ans = ans * ((fflen <= top - lst + ffl) + (fflen < top - lst + ffl)) % mod;
//	cerr << ans << endl;
}

int main() {
#ifndef ONLINE_JUDGE
    freopen("1.in","r",stdin);
#endif
    n = in; rep(i, 1, n) a[i] = in, deg[a[i]]++;
	rep(i, 1, n) if(!vis[i]) {
		int x = i; top = 0; while(!vis[x]) vis[x] = i, stk[++top] = x, x = a[x];
		if(vis[x] != i) continue;
		while(!isc[x]) isc[x] = true, x = a[x];
	}
	rep(i, 1, n) if((!isc[i] && deg[i] > 1) || deg[i] > 2) return puts("0"), 0;
	rep(i, 1, n) if(!deg[i]) { int x = i; top = 0; while(!isc[x]) top++, x = a[x]; ftlen[x] = top; }
	rep(i, 1, n) if(isc[i]) work(i);
	rep(i, 1, n) {
		if(!tot[i]) continue; // cerr << i << " " << tot[i] << endl;
		f[0] = 1;
		rep(j, 1, tot[i]) {
			if((i & 1) && i > 1) f[j] = f[j - 1] * 2ll % mod;
			else f[j] = f[j - 1];
			if(j > 1) f[j] = (f[j] + 1ll * f[j - 2] * (j - 1) % mod * i % mod) % mod;
		} 
		ans = ans * f[tot[i]] % mod;
	} cout << ans << endl;
}
